package com.youchuang.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.opensymphony.xwork2.ActionContext;
import com.youchuang.bean.Comment;
import com.youchuang.bean.ReceiveAddress;
import com.youchuang.bean.User;
import com.youchuang.common.Constant;
import com.youchuang.dao.CommentDAO;
import com.youchuang.dao.ReceiveAddressDAO;
import com.youchuang.dao.UserDAO;
import com.youchuang.mail.MailSenderInfo;
import com.youchuang.mail.SimpleMailSender;
import com.youchuang.service.UserService;
import com.youchuang.util.EmailCodeUtil;
import com.youchuang.util.ImageUtil;
import com.youchuang.util.Md5CodeUtil;

@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {

	private static final Logger logger = Logger.getLogger(UserServiceImpl.class.getSimpleName());
	@Resource
	private ReceiveAddressDAO receiveAddressDAO;
	@Resource
	private CommentDAO commentDAO;
	@Resource
	private UserDAO userDAO;

	public void saveComment(Comment comment) {
		commentDAO.save(comment);
	}

	@Override
	public void saveReceiveAddress(ReceiveAddress receiveAddress) {
		receiveAddressDAO.save(receiveAddress);

	}

	@Override
	public InputStream getImageCodeStream() {
		Map<String, BufferedImage> map = ImageUtil.createImage();
		String key = map.keySet().iterator().next();
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put(Constant.CHECK_CODE, key);
		BufferedImage image = map.get(key);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpeg", bos);
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e);
		}
		image.flush();
		byte[] imageBt = bos.toByteArray();
		InputStream imageStream = new ByteArrayInputStream(imageBt);
		return imageStream;
	}

	@Override
	public void deleteAddressActionById(String id) {
		ReceiveAddress receiveAddress = findReceiveAddressById(id);
		receiveAddressDAO.delete(receiveAddress);
	}

	@Override
	public ReceiveAddress findReceiveAddressById(String id) {
		return receiveAddressDAO.queryById(id);
	}

	@Override
	public String loginUser(User user) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
		User queryUser = userDAO.queryByEmail(user.getEmail());

		if (queryUser == null) {
			request.setAttribute(Constant.LOGIN_ERR, "账户不存在");
			return Constant.LOGIN;
		}
		if (!queryUser.getPassword().equals(Md5CodeUtil.createMd5Code(user.getPassword()))) {
			request.setAttribute(Constant.LOGIN_ERR, "用户名或密码错误");
			return Constant.LOGIN;
		}

		queryUser.setLastLoginIp(request.getRemoteAddr());
		queryUser.setLastLoginTime(System.currentTimeMillis());
		userDAO.update(queryUser);

		session.put(Constant.S_USER, queryUser);

		if (queryUser.getEmailVerify() == Constant.NOT_PASS) {

			String fulAddress = user.getEmail();
			String mainAddress = fulAddress.substring(fulAddress.lastIndexOf("@") + 1);

			String DomainAddress = mainAddress.substring(0, mainAddress.lastIndexOf("."));
			if (("163").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.163.com/");
			} else if (("126").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.126.com/");
			} else if (("sina").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.sina.com/");
			} else if (("yahoo").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.yahoo.com/");
			} else if (("sohu").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.sohu.com/");
			} else if (("yeah").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.yeah.com/");
			} else if (("gmail").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.gmail.com/");
			} else if (("hotmail").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.hotmail.com/");
			} else if (("qq").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.qq.com/");
			} else if (("139").equals(DomainAddress)) {
				session.put(Constant.MAIL_ADDRESS, "http://mail.139.com/");
			} else {
				session.put(Constant.MAIL_ADDRESS, "http://www.baidu.com.cn/");
			}
			return Constant.VERIFY;
		}

		return Constant.SUCCESS;
	}

	@Override
	public String updatePassword(String olderPassword, String password, String rePassword) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		User user = (User) session.get(Constant.S_USER);
		if (password.trim().equals(rePassword.trim())) {
			if (user.getPassword().trim().equals(Md5CodeUtil.createMd5Code(olderPassword.trim()))) {
				String pwd = Md5CodeUtil.createMd5Code(password.trim());
				User updateUser = userDAO.queryById(user.getId());
				updateUser.setEmail(user.getEmail());
				updateUser.setPassword(pwd);
				int i = userDAO.update(updateUser);
				if (i == 0) {
					return Constant.ERROR;
				} else {
					return Constant.SUCCESS;
				}
			} else {
				return Constant.ERROR;
			}
		}
		return Constant.ERROR;
	}

	@Override
	public void registUser(User user) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
		String pwd = Md5CodeUtil.createMd5Code(user.getPassword());
		user.setPassword(pwd);
		user.setUserIntegral(10);
		user.setEmailVerify(Constant.NOT_PASS);

		String emailCode = EmailCodeUtil.createEmailCode();
		user.setEmailVerifyCode(emailCode);

		user.setLastLoginTime(System.currentTimeMillis());
		user.setLastLoginIp(request.getRemoteAddr());

		userDAO.save(user);

		session.put(Constant.S_USER, user);

		MailSenderInfo mailInfo = new MailSenderInfo();
		mailInfo.setMailServerHost(Constant.MAIL_SERVERHOST);
		mailInfo.setMailServerPort(Constant.MAIL_SERVERPORT);
		mailInfo.setValidate(true);
		mailInfo.setUserName(Constant.EMAIL);
		mailInfo.setPassword(Constant.PASSWORD);
		mailInfo.setFromAddress(Constant.EMAIL);
		mailInfo.setToAddress(user.getEmail());
		mailInfo.setSubject("YOUCHUANG");
		mailInfo.setContent(user.getNickName() + ",您好，请将一下验证码填入验证框内：" + emailCode + "-" + user.getId() + " ，并完成注册！谢谢！");
		// mailInfo.setContent("谢谢！");
		SimpleMailSender sms = new SimpleMailSender();
		sms.sendTextMail(mailInfo);

		String fulAddress = user.getEmail();
		String mainAddress = fulAddress.substring(fulAddress.lastIndexOf('@') + 1);

		String domainAddress = mainAddress.substring(0, mainAddress.lastIndexOf('.'));
		if (domainAddress.equals("163")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.163.com/");
		} else if (domainAddress.equals("126")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.126.com/");
		} else if (domainAddress.equals("sina")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.sina.com/");
		} else if (domainAddress.equals("yahoo")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.yahoo.com/");
		} else if (domainAddress.equals("sohu")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.sohu.com/");
		} else if (domainAddress.equals("yeah")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.yeah.com/");
		} else if (domainAddress.equals("gmail")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.gmail.com/");
		} else if (domainAddress.equals("hotmail")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.hotmail.com/");
		} else if (domainAddress.equals("qq")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.qq.com/");
		} else if (domainAddress.equals("139")) {
			session.put(Constant.MAIL_ADDRESS, "http://mail.139.com/");
		} else {
			session.put(Constant.MAIL_ADDRESS, "http://www.baidu.com.cn/");
		}
	}

	@Override
	public void updateReceiveAddress(ReceiveAddress receiveAddress) {
		receiveAddressDAO.update(receiveAddress);
	}

	@Override
	public void updateUser(User user) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		User updateUser = userDAO.queryByEmail(user.getEmail());
		updateUser.setEmail(user.getEmail());
		updateUser.setNickName(user.getNickName());
		userDAO.update(updateUser);

		session.put(Constant.S_USER, updateUser);
	}

	@Override
	public String verifyUser(String code) {
		Map<String, Object> session = ActionContext.getContext().getSession();
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
		String uid = EmailCodeUtil.getUid(code);
		if (uid == null) {
			request.setAttribute(Constant.VERIFY_ERR, "邮箱验证码错误，请检查后重输");
			return Constant.VERIFY;
		}
		String vCode = EmailCodeUtil.getUUID(code);

		User updateUser = userDAO.queryById(uid);
		if (updateUser != null && vCode.trim().equals(updateUser.getEmailVerifyCode())) {
			updateUser.setEmailVerify(Constant.PASS);
			userDAO.update(updateUser);
			session.clear();
			session.put(Constant.S_USER, updateUser);
			return Constant.SUCCESS;
		} else {
			request.setAttribute(Constant.VERIFY_ERR, "邮箱验证码错误，请检查后重输");
			return Constant.VERIFY;
		}

	}

	@Override
	public User findUserByEmail(String email) {
		return userDAO.queryByEmail(email);
	}

	@Override
	public List<ReceiveAddress> findReceiveAddressByUserId(String userId) {
		return receiveAddressDAO.queryByUserId(userId);
	}

}
